<template>
  <div class="account-settings-info-view">
    <div class="left-Box">
      <a-card title="个人中心" style="width: 300px">
        <img :src="imgUrl+usersCenterData.avatarPath" @click="visibleAvater=true" alt="avatar" />
        <!-- <a slot="extra" href="#">more</a> -->
        <!-- <div class="img-header-Box">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="prefix+'shop/upload/uploadImage/AVATAR'"
            :headers="{'Authorization': token}"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="usersCenterData.avatarPath" :src="imgUrl+usersCenterData.avatarPath" alt="avatar" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </div> -->
        <div class="from-Box">
          <div>登录账号</div>
          <div>{{ usersCenterData.username }}</div>
        </div>
        <div class="from-Box">
          <div>用户昵称</div>
          <div>{{ usersCenterData.nickName }}</div>
        </div>
        <div class="from-Box">
          <div>手机号码</div>
          <div>{{ usersCenterData.phone }}</div>
        </div>
        <div class="from-Box">
          <div>性别</div>
          <div>{{ usersCenterData.gender }}</div>
        </div>
        <div class="from-Box">
          <div>安全设置</div>
          <div class="color-Box" @click="showModal">修改密码</div>
        </div>
        <!-- <p>用户昵称</p>
      <p>手机号码</p> -->
      </a-card>
      <br />
    </div>
    <div>
      <div class="tab-Box">
        <a-tabs default-active-key="1" @change="callback">
          <a-tab-pane key="1" tab="用户资料">
            <div class="input-Box">
              <a-form
                class="a-form-Box"
                :form="form"
                :label-col="{ span: 5 }"
                :wrapper-col="{ span: 12 }"
              >
                <a-form-item label="昵称">
                  <a-input
                    @change="nickNameChange"
                    v-decorator="[
                      'nickName',
                      {
                        rules: [
                          {
                            required: true,
                            message: '请输入你的昵称',
                          },
                        ],
                      },
                      {
                        validator: validatNumbertwo,
                      },
                    ]"
                  />
                </a-form-item>
                <!-- <div class="input-text">用户昵称不作为登录使用</div> -->
                <!-- </a-form>
              <a-form
                class="a-form-Box"
                :form="form"
                :label-col="{ span: 5 }"
                :wrapper-col="{ span: 12 }"
                @submit="handleSubmit"
              > -->
                <a-form-item label="手机号">
                  <a-input
                    @change="phoneChange"
                    v-decorator="[
                      'phone',
                      {
                        rules: [
                          {
                            required: true,
                            message: '请输入您的手机号',
                          },
                        ],
                      },
                      {
                        validator: validatNumbertwo,
                      },
                    ]"
                  />
                </a-form-item>
                <!-- <div class="input-text up">手机号码不能重复</div> -->
              </a-form>
            </div>
            <div>
              <div>
                <span style="margin: 0 20px">性别</span>
                <a-radio-group
                  v-model="usersCenterData.gender"
                  name="radioGroup"
                  default-value="男"
                  @change="radioGroupChage"
                >
                  <a-radio value="男">男</a-radio>
                  <a-radio value="女"> 女</a-radio>
                </a-radio-group>
              </div>
            </div>
            <div class="button-Box">
              <a-button type="primary" html-type="submit" @click="updateSubmit">
                保存配置
              </a-button>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="操作日志" force-render>
            <a-layout-content>
              <!-- <a-card title="角色列表" :bordered="true" type="inner"> -->
              <a-table
                :columns="columns"
                :dataSource="dataTable"
                :rowKey="(record) => record.id"
                :loading="loading"
                :pagination="false"
                bordered
              >
                <template slot="action" slot-scope="text, record">
                  <!-- <a-tag color="#933dfe" v-permission:role="['roleUpdate']" @click="getRolesMenusList(record.id)">编辑</a-tag> -->
                  <a-tag color="#933dfe" @click="getRolesMenusList(record.id)"
                    >编辑</a-tag
                  >
                  <a-tag
                    color="#f50"
                    v-permission:role="['roleDelete']"
                    @click="deleteUser(record)"
                    >删除</a-tag
                  >
                </template>
              </a-table>
            </a-layout-content>
            <div class="a-pagination">
              <a-pagination
                show-size-changer
                :default-current="3"
                @showSizeChange="onShowSizeChange"
              />
            </div>
            <!-- :total="100" -->
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <!-- 修改密码弹窗 -->
    <div>
      <a-modal v-model="visible" title="修改密码" @ok="handleOk">
        <div class="input-Box">
          <a-form
            class="a-form-Box"
            :form="form_dialog"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-form-item label="旧密码">
              <a-input-password
                class="radiu"
                size="large"
                type="password"
                autocomplete="false"
                placeholder="请输入验证码"
                @change="oldPasswordChange"
                v-decorator="[
                  'oldPassword',
                  {
                    rules: [{ required: true, message: '请输入旧密码' }],
                    validateTrigger: 'blur',
                  },
                  {
                    validator: validatNumbertwo,
                  },
                ]"
                @keyup.enter="loginVal"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  style="color: rgba(0, 0, 0, 0.25)"
                />
              </a-input-password>
            </a-form-item>
            <!-- </a-form>
          <a-form
            class="a-form-Box"
            :form="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          > -->
            <a-form-item label="新密码">
              <a-input-password
                class="radiu"
                size="large"
                type="newPassword"
                autocomplete="false"
                placeholder="请输入验证码"
                @change="newPasswordChange"
                v-decorator="[
                  'newPassword',
                  {
                    rules: [{ required: true, message: '请输入旧密码' }],
                    validateTrigger: 'blur',
                  },
                  {
                    validator: validatNumbertwo,
                  },
                ]"
                @keyup.enter="loginVal"
              >
                <a-icon
                  slot="prefix"
                  type="lock"
                  style="color: rgba(0, 0, 0, 0.25)"
                />
              </a-input-password>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
    <avatar-modal ref="modal" :visible="visibleAvater" @ok="setavatar"/>
  </div>
</template>

<script>
import { prefix, imgUrl } from '@/utils/env-setup'
import * as API from "../../api/BaseSetting";
import AvatarModal from './AvatarModal'
// import * as API from "../../api/setting";
import { mapState } from "vuex";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  components: {
    AvatarModal
  },
  data() {
    return {
      prefix,
      imgUrl,
      recordsList: [],
      pageNumber: 1,
      pageSize: 10,
      form_dialog: this.$form.createForm(this),
      // updateInfoParams: {},
      postBody: {
        newPassword: "",
        oldPassword: "",
      },
      form: this.$form.createForm(this),
      usersCenterData: {},
      visible: false, //弹窗
      visibleAvater: false, //弹窗
      //分页参数
      pageNumber: 1,
      pageSize: 5,
      current: 4,
      //分页参数
      dataTable: [],
      columns: [
        {
          title: "操作",
          dataIndex: "description",
          width: "15%",
          align: "center",
          scopedSlots: { customRender: "id" },
        },
        {
          title: "IP",
          dataIndex: "requestIp",
          width: "15%",
          align: "center",
          scopedSlots: { customRender: "name" },
        },
        {
          title: "IP地址",
          dataIndex: "address",
          width: "9%",
          align: "center",
          scopedSlots: { customRender: "description" },
        },
        {
          title: "浏览器",
          dataIndex: "browser",
          width: "11%",
          align: "center",
          scopedSlots: { customRender: "createTime1" },
        },
        {
          title: "请求耗时",
          dataIndex: "time",
          width: "11%",
          align: "center",
          scopedSlots: { customRender: "createTime2" },
        },
        {
          title: "创建日期",
          dataIndex: "createTime",
          width: "11%",
          align: "center",
          scopedSlots: { customRender: "createTime" },
        },
        // {
        //   title: "操作",
        //   dataIndex: "action",
        //   width: "15%",
        //   align: "center",
        //   scopedSlots: { customRender: "action" },
        // },
      ],
      formLayout: "horizontal",
      // form: this.$form.createForm(this, { name: "coordinated" }),
      loading: false,
      // avatarPath: "",
      phoneInputVisible: false,
      emailInputVisible: false,
      pwdInputVisible: false,
      phoneInputValue: null,
      emailInputValue: null,
      oldPassword: null,
      newPassword: null,
      loading: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    ...mapState({
      token: (state) => state.user.token
    }),
  },
  mounted() {
    this.usersCenterList();
    this.logsUserList();
  },
  created() {
    this.initPut();
    // console.log(this.imgUrl, 55555)
  },
  methods: {
    validatNumbertwo(rule, value, callback) {
      if (!isNull(value)) {
        callback();
      } else {
        callback("密码不能为空");
      }
    },
    setFields(submitData) {
      // form 回写
      // this.updateInfoParams.nickName = submitData.nickName
      // this.updateInfoParams.phone = submitData.phone
      // this.updateInfoParams.gender = submitData.gender
      this.form.setFieldsValue({
        phone: submitData.phone || undefined,
        nickName: submitData.nickName || undefined,
      });
    },
    logsUserList(current, pageSize) {
      let params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
      };
      API.logsUser(params).then((res) => {
        this.dataTable = res.data.records;
      });
    },
    updateSubmit() {
      //  this.form.setFieldsValue({
      //   phone: submitData.phone || undefined,
      //   nickName: submitData.nickName || undefined,
      //   // remark: submitData.remark || undefined,
      //   // num: submitData.num || undefined
      // });
      // console.log(this.updateInfoParams, this.avatarPath)
      this.form.validateFields((err) => {
        if (!err) {
          this.loading = true;
          // let params = {
          //   nickName: this.updateInfoParams.nickName,
          //   phone: this.updateInfoParams.phone,
          //   gender: this.updateInfoParams.gender,
          //   avatarPath: this.updateInfoParams.avatarPath
          // };
          API.centerUpdate(this.usersCenterData).then((res) => {
            if (res.code == 200) {
              this.$message.success("修改成功");
              this.usersCenterList();
            }
            this.loading = false;
            this.visibleAvater = false
          });

          // console.log(this.updateInfoParams);
        }
      });
    },
    radioGroupChage(e) {
      this.usersCenterData.gender = e.target.value;
      console.log(e.target.value);
    },
    phoneChange(e) {
      this.usersCenterData.phone = e.target.value;
      console.log(e.target.value);
    },
    nickNameChange(e) {
      this.usersCenterData.nickName = e.target.value;
      console.log(e.target.value);
    },
    newPasswordChange(e) {
      console.log(e.target.value);
      this.newPassword = e.target.value;
    },
    oldPasswordChange(e) {
      this.oldPassword = e.target.value;
    },
    // newPassword(e){
    //     this.postBody.newPassword = e.target.value;
    // },
    showModal() {
      this.oldPassword = "";
      this.newPassword = "";
      // console.log( this.oldPassword ,"nnnnnnnnnn")
      this.form_dialog.setFieldsValue({
        oldPassword: "",
        newPassword: "",
        // remark: submitData.remark || undefined,
        // num: submitData.num || undefined
      });
      this.visible = true;
    },
    handleOk(e) {
      this.loading = true;
      this.form_dialog.validateFields((err) => {
        if (!err) {
          console.log(this.form, "sssssssss");
          let params = {
            oldPassword: this.oldPassword,
            newPassword: this.newPassword,
          };
          API.usersPassword(params).then((res) => {
            console.log(res);
            if (res.code == 200) {
              // this.$message.success(res.desc)
            } else {
              // this.$message.error(res.desc)
            }
            this.loading = false;
          });
          this.visible = false;
        }
      });
    },

    //分页监听
    onShowSizeChange(current, pageSize) {
      this.pageNumber = current;
      this.pageSize = pageSize;
      this.logsUserList(current, pageSize);
      console.log(current, pageSize);
    },
    usersCenterList() {
      // 列表
      this.loading = true;
      API.usersCenter().then((res) => {
        if (res.code === 200) {
          console.log(res);
          this.usersCenterData = res.data;
          this.setFields(this.usersCenterData);
        }
        this.loading = false;
      });
    },
    //提交
    handleSubmit(e) {
      console.log(this.form, "sssssssssssssss");
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
        }
      });
    },
    //头像上传
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file && (info.file.status === 'done')) {
        this.usersCenterData.avatarPath = info.file?info.file.response.data.path : ''
        this.updateSubmit()
      }
      // if (info.file.status === "done") {
        // Get this url from response in real world.
        // debugger
        // getBase64(info.file.originFileObj, (avatarPath) => {
        //   this.avatarPath = avatarPath;
        //   this.loading = false;
        //   debugger
        //   this.updateSubmit()
        // });
      // }
    },
    setavatar(str){
      this.usersCenterData.avatarPath = str
      // debu
      this.updateSubmit()
    },
    callback(key) {
      console.log(key);
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    //头像上传
    initPut() {
      this.phoneInputValue = this.userInfo.phone;
      this.emailInputValue = this.userInfo.email;
    },
    edit(status) {
      let id = this.userInfo.id;
      let putBody = {
        username: this.userInfo.username,
        phone: this.userInfo.phone,
        email: this.userInfo.email,
        roleId: this.userInfo.role.id,
      };
      status === "phone" && (putBody.phone = this.phoneInputValue);
      status === "email" && (putBody.email = this.emailInputValue);
      API.editUser(id, putBody).then((res) => {
        if (res.code === 200) {
          this.$message.destroy();
          this.$message.success("操作成功");
          this.getInfoList();
        }
      });
    },
    pwdConfirm() {
      this.loading = true;
      let pwdBody = {
        oldPassword: this.oldPassword,
        newPassword: this.newPassword,
      };
      API.editPwd(pwdBody)
        .then((res) => {
          if (res.code === 200) {
            this.$message.destroy();
            this.$message.success("密码修改成功");
            this.pwdCancel();
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getInfoList() {
      // 获取用户基本信息
      API.getInfo()
        .then((res) => {
          if (res.code === 200) {
            this.$store.dispatch("updateUserInfo", res.data).then(() => {
              this.initPut();
            });
          } else {
            this.loginLoading = false;
          }
        })
        .catch(() => {
          this.loginLoading = false;
        });
    },
    showPhoneInput() {
      this.phoneInputVisible = true;
      this.$nextTick(() => {
        this.$refs.phoneInput.focus();
      });
    },
    showEmailInput() {
      this.emailInputVisible = true;
      this.$nextTick(() => {
        this.$refs.emailInput.focus();
      });
    },
    showPwdInput() {
      // console.log(111)
      this.pwdInputVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.pwdInput.focus();
      // })
    },
    phoneInputChange(e) {
      this.phoneInputValue = e.target.value;
    },

    phoneTagInputConfirm() {
      this.phoneInputVisible = false;
      this.edit("phone");
    },
    emailInputChange(e) {
      this.emailInputValue = e.target.value;
    },

    emailTagInputConfirm() {
      this.emailInputVisible = false;
      this.edit("email");
    },

    pwdCancel() {
      this.oldPassword = null;
      this.newPassword = null;
      this.pwdInputVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.ant-card-body img {
  width: 100px;
  min-height: 100px;
    margin: 0 auto;
    display: block;
}
.account-settings-info-view {
  display: flex;
  .iconEdit {
    padding-left: 10px;
    // color: @redColor;
  }
}
.from-Box {
  display: flex;
  justify-content: space-between;
  line-height: 40px;
  border-bottom: 1px solid #f0f3f4;
}
.img-header-Box {
  width: 102px;
  height: 102px;
  margin: 0 auto;
  margin-bottom: 20px;
}
.color-Box {
  cursor: pointer;
  color: #317ef3;
}
.left-Box {
  margin-right: 40px;
}
.a-form-Box {
  position: relative;
}
.input-text {
  color: rgb(192, 192, 192);
  position: absolute;
  right: 15px;
  top: 10px;
}
.up {
  position: absolute;
  right: 56px;
  top: 10px;
}
.tab-Box {
  width: 900px;
}
.input-Box {
  width: 600px;
  // background-color: pink;
  margin-left: -60px;
}
.button-Box {
  margin: 20px;
  margin-left: 65px;
}
.a-pagination {
  margin: 20px 0;
}
</style>
